package logic

import (
	"context"
	"errors"
	"manuscript-service/model/mysql"

	"manuscript-service/bookrpc/bookrpc"
	"manuscript-service/bookrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookAddLogic {
	return &BookAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 稿件新增
func (l *BookAddLogic) BookAdd(in *bookrpc.BookAddRequest) (*bookrpc.BookAddResponse, error) {
	// todo: add your logic here and delete this line

	var findClass mysql.Book

	tx := mysql.DB.Begin()

	err := findClass.FindClass(tx, in.Title)
	if err == nil {
		tx.Rollback()
		return nil, errors.New("稿件名称已存在")
	}

	class := mysql.Class{
		Name: in.ClassName,
	}

	err = class.FindClassByName(tx, in.ClassName)
	if err != nil {
		tx.Rollback()
		return nil, err
	}

	book := mysql.Book{
		Title:   in.Title,
		Author:  in.Author,
		Content: in.Content,
		ClassId: int(class.ID),
	}

	err = book.BookAdd(tx)
	if err != nil {
		tx.Rollback()
		return nil, err
	}

	tx.Commit()

	return &bookrpc.BookAddResponse{
		BookId: int64(book.ID),
	}, nil
}
